package com.service.system.staticRole.impl;

import com.dao.StaticPermissionMapper;
import com.dao.StaticRoleMapper;
import com.dao.StaticRolePermissionMapper;
import com.dao.StaticUserRoleMapper;
import com.entity.system.StaticPermission;
import com.entity.system.StaticRole;
import com.entity.system.StaticRolePermission;
import com.entity.system.StaticUserRole;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.system.staticRole.StaticRoleService;
import com.util.Const;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StaticRoleServiceImpl implements StaticRoleService{

    @Autowired
    StaticRoleMapper staticRoleMapper;

    @Autowired
    StaticUserRoleMapper staticUserRoleMapper;

    @Autowired
    StaticRolePermissionMapper staticRolePermissionMapper;

    @Autowired
    StaticPermissionMapper staticPermissionMapper;



    @Override
    public Map<String, Object> findRoleList(String pageNum, String pageSize) {
        Map<String,Object> map = new HashMap<String, Object>();
        if(StringUtils.isEmpty(pageNum)){
            pageNum = "1";
        }
        if(StringUtils.isEmpty(pageSize)){
            pageSize = "10";
        }
        map.put("roleCode","%NEW_ROLE_AGENT%");
        PageHelper.startPage(Integer.parseInt(pageNum),Integer.parseInt(pageSize));
        List<StaticRole> list = staticRoleMapper.findRoleByMap(map);
        PageInfo<StaticRole> pageInfo = new PageInfo<>(list);
        map.clear();
        map.put("code", Const.SUCCESS_CODE);
        map.put("message","查询成功");
        map.put("page",pageInfo);
        map.put("staticRoles",pageInfo.getList());
        return map;
    }

    @Override
    public Map<String, Object> findPermissions(Long roleId) {
        Map<String,Object> map = new HashMap<>();
//        StaticUserRole staticUserRole = staticUserRoleMapper.selectByUserId(userId);
        List<Long> permissionIds = staticRolePermissionMapper.findPermissionIdByRoleId(roleId);
        StaticRole staticRole = staticRoleMapper.selectByPrimaryKey(roleId);
        map.put("permissionType",1);
        map.put("permissionParent",0);
        List<StaticPermission> permissionList = staticPermissionMapper.findStaticPermissionByIdAndType(map);
        map.clear();
        for (StaticPermission sp : permissionList) {
            //是否有一级菜单权限
            if(permissionIds.contains(sp.getId())){
                sp.setMenuPermissions(1);
            }
            map.put("permissionParent",sp.getId());
            map.put("permissionMenu",1);
            List<StaticPermission> sps = staticPermissionMapper.findStaticPermissionByIdAndType(map);
            for(StaticPermission ss : sps){
                //是否有二级菜单权限
                if(permissionIds.contains(ss.getId())){
                    ss.setMenuPermissions(1);
                }
                //是否有增删改查权限
                if(StringUtils.isNotEmpty(staticRole.getAddPermission())){
                    if(new BigInteger(staticRole.getAddPermission()+"").testBit(Integer.parseInt(ss.getId()+""))){
                        ss.setAdd(1);
                    }
                }
                if(StringUtils.isNotEmpty(staticRole.getDelPermission())){
                    if(new BigInteger(staticRole.getDelPermission()+"").testBit(Integer.parseInt(ss.getId()+""))){
                        ss.setDel(1);
                    }
                }
                if(StringUtils.isNotEmpty(staticRole.getChangePermission())){
                    if(new BigInteger(staticRole.getChangePermission()+"").testBit(Integer.parseInt(ss.getId()+""))){
                        ss.setEdit(1);
                    }
                }
                if(StringUtils.isNotEmpty(staticRole.getQueryPermission())){
                    if(new BigInteger(staticRole.getQueryPermission()+"").testBit(Integer.parseInt(ss.getId()+""))){
                        ss.setQuery(1);
                    }
                }

            }
            sp.setList(sps);
        }
        map.clear();
        map.put("code",1);
        map.put("menus",permissionList);
        map.put("message","查询成功");
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> updatePermissions(Map<String, String> map){
        Map<String,Object> map1 = new HashMap<String, Object>();
        Long roleId = Long.parseLong(map.get("roleId"));
        String[] pids = null;
        String[] cids = null;
        if(StringUtils.isNotEmpty(map.get("pids"))){
            pids = map.get("pids").split(",");
        }
        if(StringUtils.isNotEmpty(map.get("cids"))){
            cids = map.get("cids").split(",");
        }

        String[] menuIds =(String[]) ArrayUtils.addAll(pids,cids);

        //删除原有角色权限
        List<Long> permissionIds = staticRolePermissionMapper.findPermissionIdByRoleId(roleId);
        if(permissionIds.size() > 0){
            int num = staticRolePermissionMapper.deleteByRoleId(roleId);
            if(num <= 0){
                map1.put("code",Const.ERROR_CODE);
                map1.put("message","修改失败");
                return map1;
            }
        }
        //添加新的角色权限
        if(null != menuIds){
            Arrays.sort(menuIds);
            for(int i = 0;i < menuIds.length;i++){
                StaticRolePermission staticRolePermission = new StaticRolePermission();
                staticRolePermission.setRoleId(roleId);
                staticRolePermission.setPermissionId(Long.parseLong(menuIds[i]));
                staticRolePermission.setRolePermissionNote("角色权限分配");
                int num = staticRolePermissionMapper.insert(staticRolePermission);
            }
        }

        //修改增删改查权限
        StaticRole staticRole = new StaticRole();
        staticRole.setRoleId(roleId);
        if(StringUtils.isEmpty(map.get("qids"))){
            staticRole.setQueryPermission("");
        }else {
            staticRole.setQueryPermission(Calculation(map.get("qids").split(","))+"");
        }
        if(StringUtils.isEmpty(map.get("aids"))){
            staticRole.setAddPermission("");
        }else {
            staticRole.setAddPermission(Calculation(map.get("aids").split(","))+"");
        }
        if(StringUtils.isEmpty(map.get("dids"))){
            staticRole.setDelPermission("");
        }else {
            staticRole.setDelPermission(Calculation(map.get("dids").split(","))+"");
        }
        if(StringUtils.isEmpty(map.get("eids"))){
            staticRole.setChangePermission("");
        }else {
            staticRole.setChangePermission(Calculation(map.get("eids").split(","))+"");
        }
        int num = staticRoleMapper.updateByPrimaryKeySelective(staticRole);

        if(num == 1){
            map1.put("code",Const.SUCCESS_CODE);
            map1.put("message","修改成功");
        }else {
            map1.put("code",Const.ERROR_CODE);
            map1.put("message","修改失败");
        }
        return map1;
    }

    //Bit计算方法
    public BigInteger Calculation(String[] strings){
        BigInteger num =  num = new BigInteger("0");
        int length = strings.length;
        for (int i =0;i<length;i++) {
            num = num.setBit(Integer.parseInt(strings[i]));
        }
        return num;
    }

    @Override
    public Map<String, Object> findRoleAndUserRole(String userId) {
        Map<String,Object> map = new HashMap<>();
        map.put("roleCode","%NEW_ROLE_AGENT%");
        List<StaticRole> staticRoles = staticRoleMapper.findRoleByMap(map);
        map.clear();
        map.put("userId",userId);
        map.put("differentiate",1);
        StaticUserRole staticUserRole = staticUserRoleMapper.findStaticUserRoleByMap(map);
        map.clear();
        map.put("code",Const.SUCCESS_CODE);
        map.put("message","查询成功");
        map.put("list",staticRoles);
        map.put("staticUserRole",staticUserRole);
        return map;
    }

    @Override
    public Map<String, Object> roleDistribution(Map<String, String> map) {
        Map<String,Object> map1 = new HashMap<>();
        int num = 0;
        map1.put("userId",map.get("userId"));
        map1.put("differentiate",1);
        StaticUserRole staticUserRole = staticUserRoleMapper.findStaticUserRoleByMap(map1);
        //如果用户原来有角色信息并且所选角色不为空做update处理
        if(null != staticUserRole && StringUtils.isNotEmpty(map.get("roleId"))){
            staticUserRole.setRoleId(Long.parseLong(map.get("roleId")));
            staticUserRole.setUserId(Long.parseLong(map.get("userId")));
            staticUserRole.setUserPhone(map.get("phone"));
            staticUserRole.setUserRoleNote(map.get("roleName"));
            staticUserRole.setDifferentiate(1);
            num = staticUserRoleMapper.updateByPrimaryKeySelective(staticUserRole);
            //如果用户原来有角色信息并且所选角色为空做delete处理
        }else if(null != staticUserRole && StringUtils.isEmpty(map.get("roleId"))){
            map1.put("userId",map.get("userId"));
            map1.put("differentiate",1);
            num = staticUserRoleMapper.delByMap(map1);
            //如果用户原来没有角色信息并且所选角色不为空做insert处理
        }else if(null == staticUserRole && StringUtils.isNotEmpty(map.get("roleId"))){
            staticUserRole = new StaticUserRole();
            staticUserRole.setRoleId(Long.parseLong(map.get("roleId")));
            staticUserRole.setUserId(Long.parseLong(map.get("userId")));
            staticUserRole.setUserPhone(map.get("phone"));
            staticUserRole.setUserRoleNote(map.get("roleName"));
            staticUserRole.setDifferentiate(1);
            num = staticUserRoleMapper.insertSelective(staticUserRole);
        }
        if(num == 1){
            map1.put("code",Const.SUCCESS_CODE);
            map1.put("message","分配成功");
        }else {
            map1.put("code",Const.ERROR_CODE);
            map1.put("message","分配失败");
        }
        return map1;
    }

    @Override
    public Map<String, Object> addRole(String roleName, String roleNote, String roleCode) {
        Map<String,Object> map = new HashMap<>();
        StaticRole staticRole = new StaticRole();
        staticRole.setRoleName(roleName);
        staticRole.setRoleNote(roleNote);
        staticRole.setRoleCode(roleCode);
        int num = staticRoleMapper.insert(staticRole);
        if(num == 1){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","添加成功");
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","添加失败");
        }
        return map;
    }

    @Override
    public StaticUserRole getUserRoleByUserId(Long userId) {
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("differentiate",1);
        return staticUserRoleMapper.findStaticUserRoleByMap(map);
    }

    @Override
    public StaticRole getRoleByRoleId(Long roleId) {
        return staticRoleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public Map<String, Object> updateRole(StaticRole staticRole) {
        Map<String,Object> map = new HashMap<>();
        int num = staticRoleMapper.updateByPrimaryKeySelective(staticRole);
        if(num == 1){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","修改成功");
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","修改失败");
        }
        return map;
    }

    @Override
    public StaticUserRole findStaticUserRoleByMap(Map<String, Object> map) {
        return staticUserRoleMapper.findStaticUserRoleByMap(map);
    }
}
